import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/utils/api'
import auth from './modules/auth'
import projects from './modules/projects'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // User related state
    user: null,
    token: localStorage.getItem('token') || null,
    
    // Projects related state
    projects: [],
    currentProject: null,
    loading: false,
    error: null
  },
  
  getters: {
    isAuthenticated: state => !!state.token,
    isResearcher: state => state.user && state.user.role === 'RESEARCHER',
    isParticipant: state => state.user && state.user.role === 'PARTICIPANT',
    isAdmin: state => state.user && state.user.role === 'ADMIN',
    currentUser: state => state.user,
    // 检查用户是否是项目的创建者
    isProjectCreator: (state) => (projectResearcherId) => {
      return state.user && state.user.id === projectResearcherId;
    },
    // 检查用户是否可以编辑项目（项目创建者或管理员）
    canEditProject: (state, getters) => (projectResearcherId) => {
      return getters.isAdmin || getters.isProjectCreator(projectResearcherId);
    },
    // 检查用户是否可以删除项目（项目创建者或管理员）
    canDeleteProject: (state, getters) => (projectResearcherId) => {
      return getters.isAdmin || getters.isProjectCreator(projectResearcherId);
    }
  },
  
  mutations: {
    // Auth mutations
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    
    SET_USER(state, user) {
      state.user = user
    },
    
    // Projects mutations
    SET_LOADING(state, status) {
      state.loading = status
    },
    
    SET_ERROR(state, error) {
      state.error = error
    },
    
    SET_PROJECTS(state, projects) {
      // 检查projects是否为数组且不为空
      if (!Array.isArray(projects)) {
        console.error('SET_PROJECTS mutation接收到非数组数据:', projects);
        state.projects = [];
        return;
      }

      // 处理每个项目数据，确保格式一致
      const processedProjects = projects.map(project => {
        if (!project) return null;
        
        // 基本项目信息
        return {
          id: project.id || '',
          title: project.title || '无标题',
          description: project.description || '',
          
          // 研究者信息
          researcherInfo: project.researcherInfo || { 
            name: '', 
            affiliation: '', 
            contactInfo: '' 
          },
          
          // 日期处理
          createdAt: project.createdAt || null,
          updatedAt: project.updatedAt || project.createdAt || null,
          deletedAt: project.deletedAt || null,
          
          // 状态标志
          isCompleted: !!project.isCompleted,
          isDeleted: !!project.isDeleted,
          
          // 其他元数据
          dataRequirements: project.dataRequirements || '',
          ethicalApproval: !!project.ethicalApproval,
          deletionReason: project.deletionReason || '',
          
          // 交易记录
          transactions: Array.isArray(project.transactions) ? project.transactions : []
        };
      }).filter(project => project !== null);

      state.projects = processedProjects;
    },
    
    SET_CURRENT_PROJECT(state, project) {
      state.currentProject = project
    },
    
    ADD_PROJECT(state, project) {
      state.projects.push(project)
    },
    
    UPDATE_PROJECT(state, updatedProject) {
      const index = state.projects.findIndex(p => p.id === updatedProject.id)
      if (index !== -1) {
        state.projects.splice(index, 1, updatedProject)
      }
      if (state.currentProject && state.currentProject.id === updatedProject.id) {
        state.currentProject = updatedProject
      }
    },
    
    DELETE_PROJECT(state, projectId) {
      if (!state.projects || !Array.isArray(state.projects)) {
        console.warn('尝试从非数组的projects中删除项目', state.projects);
        // 如果projects不是数组，初始化它
        state.projects = [];
        return;
      }

      state.projects = state.projects.filter(p => p.id !== projectId);
      if (state.currentProject && state.currentProject.id === projectId) {
        state.currentProject = null;
      }
    }
  },
  
  actions: {
    // Auth actions
    async login({ commit }, credentials) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await api.post('/auth/login', credentials)
        const { token, user } = response.data
        
        commit('SET_TOKEN', token)
        commit('SET_USER', user)
        
        return { success: true }
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || 'Authentication failed')
        return { success: false, error: error.response?.data?.message || 'Authentication failed' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async register({ commit }, userData) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        await api.post('/auth/register', userData)
        
        return { success: true }
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || 'Registration failed')
        return { success: false, error: error.response?.data?.message || 'Registration failed' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchCurrentUser({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await api.get('/users/me')
        commit('SET_USER', response.data)
        
        return { success: true }
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || 'Failed to fetch user')
        return { success: false }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    logout({ commit }) {
      commit('SET_TOKEN', null)
      commit('SET_USER', null)
    },
    
    // Projects actions
    async fetchProjects({ commit }, forceRefresh = true) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('正在请求项目列表...' + (forceRefresh ? '(强制刷新)' : ''));
        const response = await api.get('/projects/list', {
          headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' },
          params: { _t: new Date().getTime() } // 添加时间戳防止缓存
        });
        console.log('项目列表响应:', response.data)
        
        // 转换后端返回的项目列表格式
        const projects = response.data.map(item => {
          // 获取basic1和basic2字段中的数据
          const basic1Values = item.basic1 || []
          const basic2Values = item.basic2 || []
          
          return {
            id: item.id,
            title: basic1Values[0] || '未命名项目',  // 标题
            description: basic1Values[1] || '暂无描述', // 描述
            researcherInfo: basic1Values[2] || '暂无研究者信息', // 研究者信息
            // 假设创建者ID是basic1的第四个元素，也可能需要调整
            creatorId: basic1Values[3] || 'unknown',
            status: basic2Values[0] || 'ACTIVE', // 默认设为ACTIVE而不是UNKNOWN
            createdAt: basic2Values[1] ? new Date(parseInt(basic2Values[1]) * 1000) : null,
            lastUpdateTime: basic2Values[2] ? new Date(parseInt(basic2Values[2]) * 1000) : null
          }
        })
        
        console.log('转换后的项目数据:', projects)
        commit('SET_PROJECTS', projects)
        
        return { success: true }
      } catch (error) {
        console.error('获取项目列表失败:', error)
        commit('SET_ERROR', error.response?.data || '获取项目列表失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchProject({ commit }, projectId) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('获取项目详情，ID:', projectId);
        
        try {
          // 使用正确的API路径格式
          const [basic1Response, basic2Response, timesResponse] = await Promise.all([
            api.get(`/api/medical-crowdsourcing/projects/${projectId}/basic1`),
            api.get(`/api/medical-crowdsourcing/projects/${projectId}/basic2`),
            api.get(`/api/medical-crowdsourcing/projects/${projectId}/times`)
          ]);
          
          // 从API响应组装项目数据
          const project = {
            id: projectId,
            title: basic1Response.data[0] || '未命名项目',
            description: basic1Response.data[1] || '暂无描述',
            researcherInfo: basic1Response.data[2] || '暂无研究者信息',
            // 添加必要的字段
            researcherId: localStorage.getItem('userId') || null,
            completed: basic2Response.data[0] || false,
            isDeleted: basic2Response.data[1] || false,
            creationTime: timesResponse.data[0] ? parseInt(timesResponse.data[0]) : null,
            lastUpdateTime: timesResponse.data[1] ? parseInt(timesResponse.data[1]) : null,
            deletionTime: timesResponse.data[2] ? parseInt(timesResponse.data[2]) : null,
            deletionReason: basic2Response.data[2] || '',
            dataHash: basic2Response.data[3] || '',
            // 处理日期显示
            createdAt: timesResponse.data[0] ? new Date(parseInt(timesResponse.data[0])) : null,
            lastUpdatedAt: timesResponse.data[1] ? new Date(parseInt(timesResponse.data[1])) : null,
            deletedAt: timesResponse.data[2] ? new Date(parseInt(timesResponse.data[2])) : null
          };
          
          // 设置项目状态
          if (project.isDeleted) {
            project.status = 'DELETED';
          } else if (project.completed) {
            project.status = 'COMPLETED';
          } else {
            project.status = 'ACTIVE';
          }
          
          commit('SET_CURRENT_PROJECT', project);
          return project;
        } catch(error) {
          console.error('获取项目详情失败:', error);
          throw error;
        }
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || 'Failed to fetch project details')
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async createProject({ commit, dispatch }, projectData) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        // 使用相对路径和正确的API请求格式
        const response = await api.post('/projects', {
          _title: projectData.title,
          _description: projectData.description,
          _researcherInfo: projectData.researcherInfo
        })
        
        // 获取新创建的项目
        await dispatch('fetchProjects');
        
        return { success: true, project: response.data }
      } catch (error) {
        console.error('创建项目失败:', error)
        commit('SET_ERROR', error.response?.data?.message || 'Failed to create project')
        return { success: false, error: error.response?.data?.message || 'Failed to create project' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async updateProject({ commit, dispatch }, { projectId, data }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        // 使用正确的字段名格式（带下划线前缀）
        const updateData = {
          _projectId: parseInt(projectId),
          _title: data.title,
          _description: data.description,
          _researcherInfo: data.researcherInfo,
          _updateReason: data.updateReason || "更新项目信息"
        };
        
        console.log('更新项目数据:', updateData);
        // 将PUT请求改为POST请求，并更新路径
        await api.post(`/projects/${projectId}/update`, updateData);
        
        // 重新获取项目信息
        await dispatch('fetchProject', projectId);
        
        return { success: true }
      } catch (error) {
        console.error('更新项目失败:', error);
        commit('SET_ERROR', error.response?.data?.message || 'Failed to update project')
        return { success: false, error: error.response?.data?.message || 'Failed to update project' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async deleteProject({ commit }, { projectId, reason }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('删除项目，准备发送请求:', { projectId, reason });
        
        // 改为POST请求，并发送正确格式的请求体
        const response = await api.post(`/projects/${projectId}/delete`, {
          _projectId: parseInt(projectId),
          _deleteReason: reason || "删除项目"
        });
        
        console.log('删除项目响应:', response.data);
        
        try {
          commit('DELETE_PROJECT', projectId)
        } catch (mutationError) {
          console.error('删除项目mutation失败:', mutationError);
          // 继续执行，不终止流程
        }
        
        return { success: true, data: response.data }
      } catch (error) {
        console.error('删除项目API请求失败:', error);
        const errorMsg = error.response?.data?.message || 'Failed to delete project';
        commit('SET_ERROR', errorMsg)
        return { success: false, error: errorMsg }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async contributeToProject({ commit, dispatch }, { projectId, contribution }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        // 这个需要根据后端API添加
        const response = await api.post(`/projects/${projectId}/contributions`, contribution)
        
        // 更新项目信息
        await dispatch('fetchProject', projectId);
        
        return { success: true, contribution: response.data }
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.message || 'Failed to submit contribution')
        return { success: false, error: error.response?.data?.message || 'Failed to submit contribution' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchTransactionDetails({ commit }, txHash) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('获取交易详情:', txHash)
        const response = await api.get(`/transactions/${txHash}`)
        
        return { success: true, details: response.data }
      } catch (error) {
        console.error('获取交易详情失败:', error)
        commit('SET_ERROR', error.response?.data || '获取交易详情失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async verifyProjectHash({ commit }, { projectId, hash }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('验证项目哈希:', projectId, hash)
        const response = await api.post(`/projects/${projectId}/verify-hash`, { _hash: hash })
        
        // 假设响应中包含验证结果
        const isValid = response.data && response.data[0] === true
        
        return { success: true, isValid }
      } catch (error) {
        console.error('验证项目哈希失败:', error)
        commit('SET_ERROR', error.response?.data || '验证项目哈希失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async completeProject({ commit, dispatch }, projectId) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        await api.post(`/projects/${projectId}/complete`, {})
        
        // 重新获取项目信息
        await dispatch('fetchProject', projectId)
        
        return { success: true }
      } catch (error) {
        console.error('完成项目失败:', error)
        commit('SET_ERROR', error.response?.data || '完成项目失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchHistoryRecords({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('获取历史记录列表')
        const response = await api.get('/history/list')
        console.log('历史记录响应:', response.data)
        
        return { success: true, records: response.data }
      } catch (error) {
        console.error('获取历史记录失败:', error)
        commit('SET_ERROR', error.response?.data || '获取历史记录失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchProjectStatistics({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        console.log('获取项目统计数据')
        // 修复URL路径重复问题
        const response = await axios.get('/statistics/projects')
        console.log('项目统计数据响应:', response.data)
        
        return { success: true, statistics: response.data }
      } catch (error) {
        console.error('获取项目统计数据失败:', error)
        commit('SET_ERROR', error.response?.data || '获取项目统计数据失败')
        return { success: false, error }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取活跃项目列表（未删除的项目）
    async fetchActiveProjects({ commit }) {
      try {
        commit('SET_LOADING', true)
        commit('SET_ERROR', null)
        
        const response = await axios.get('http://localhost:8080/api/medical-crowdsourcing/projects/active')
        
        // 数据成功返回
        if (response.status === 200) {
          commit('SET_PROJECTS', response.data)
          return { success: true, projects: response.data }
        } else {
          commit('SET_ERROR', '获取项目列表失败: ' + response.statusText)
          return { success: false, error: response.statusText }
        }
      } catch (error) {
        console.error('获取活跃项目列表失败:', error)
        commit('SET_ERROR', error.message || '获取项目列表失败')
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取所有项目列表（包括已删除的）
    async fetchAllProjects({ commit }) {
      try {
        commit('SET_LOADING', true)
        
        const response = await axios.get('http://localhost:8080/api/medical-crowdsourcing/projects/all')
        
        // 数据成功返回
        if (response.status === 200) {
          return { success: true, projects: response.data }
        } else {
          return { success: false, error: response.statusText }
        }
      } catch (error) {
        console.error('获取所有项目列表失败:', error)
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 从区块链直接获取项目列表
    async fetchBlockchainProjects({ commit }) {
      try {
        commit('SET_LOADING', true)
        
        const response = await axios.get('http://localhost:8080/api/medical-crowdsourcing/projects/blockchain')
        
        // 数据成功返回
        if (response.status === 200) {
          commit('SET_PROJECTS', response.data)
          return { success: true, projects: response.data }
        } else {
          commit('SET_ERROR', '获取区块链项目失败: ' + response.statusText)
          return { success: false, error: response.statusText }
        }
      } catch (error) {
        console.error('获取区块链项目失败:', error)
        commit('SET_ERROR', error.message || '获取区块链项目失败')
        return { success: false, error: error.message }
      } finally {
        commit('SET_LOADING', false)
      }
    }
  },
  
  modules: {
    auth,
    projects
  }
}) 